package com.ddm.controller.vx;

import com.ddm.dto.page.PageQueryDTO;
import com.ddm.enumeration.AnnouncementType;
import com.ddm.exception.DataErrorException;
import com.ddm.result.PageResult;
import com.ddm.result.Result;
import com.ddm.service.vxService.AnnouncementService;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user/announcement")
@Slf4j
@Api("公告接口")
public class VXAnnouncementController {

    @Autowired
    AnnouncementService announcementService;

    @GetMapping
    @ApiOperation("分页获取公告")
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public Result<PageResult> getAnnouncementList(PageQueryDTO pageQueryDTO){
        log.info("分页获取公告");
        return Result.success(announcementService.getAnnouncementList(pageQueryDTO));
    }

    @GetMapping("/type/{type}")
    @ApiOperation("根据类型分页获取公告")
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public Result<PageResult> getAnnouncementListByType(PageQueryDTO pageQueryDTO, @PathVariable String type){
        log.info("根据类型分页获取公告:{}", type);
        AnnouncementType announcementType;
        try {
            // 先尝试按数字解析
            int typeValue = Integer.parseInt(type);
            announcementType = getAnnouncementTypeByValue(typeValue);
        } catch (NumberFormatException e) {
            // 如果不是数字，尝试按枚举名称解析
            try {
                announcementType = AnnouncementType.valueOf(type.toUpperCase());
            } catch (IllegalArgumentException ex) {
                throw new DataErrorException("无效的公告类型");
            }
        }
        return Result.success(announcementService.getAnnouncementListByType(pageQueryDTO, announcementType));
    }

    private AnnouncementType getAnnouncementTypeByValue(int value) {
        for (AnnouncementType type : AnnouncementType.values()) {
            if (type.getValue() == value) {
                return type;
            }
        }
        throw new DataErrorException("无效的公告类型值");
    }

}
